//用户相关接口

const express = require('express')
const router = express.Router()
const app = express()
app.use(express.urlencoded({ extended: true }))
const db = require('../utils/db')
const jwt = require('jsonwebtoken')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })

//用户登录
router.post('/admin/user/login', (req, res) => {
    // console.log(req.body)
    const { username, password } = req.body
    db(`SELECT * FROM users WHERE username='${username}' AND password=${password}`, (err, data) => {
        // console.log(data)
        if (err || data.length === 0) return res.send({ code: 400, msg: '用户名或密码出错' })
        let token = jwt.sign({ id: data[0].id }, 'haha', { expiresIn: '2h' })
        res.send({ code: 200, msg: '登录成功', token: 'Bearer ' + token })
    })
})

//获取用户信息
router.get('/admin/user/info', (req, res) => {
    // console.log(req.user)
    const { id } = req.user
    db(`SELECT nickname,userPic FROM users WHERE id='${id}'`, (err, data) => {
        if (err || data.length === 0) return res.send({ code: 400, msg: '用户信息获取失败' })
        res.send({ code: 200, msg: '获取成功', data: data[0] })
    })
})

//获取用户详情
router.get('/admin/user/detail', (req, res) => {
    const { id } = req.user
    db(`SELECT nickname,userPic,username,email,password FROM users WHERE id='${id}'`, (err, data) => {
        if (err || data.length === 0) return res.send({ code: 400, msg: '用户信息获取失败' })
        res.send({ code: 200, msg: '获取成功', data: data[0] })
    })
})

//编辑用户信息
router.post('/admin/user/edit', upload.single('userPic'), (req, res) => {
    // console.log(req.body)    
    // console.log(req.file)    
    const { username, password, email, nickname } = req.body
    const { filename } = req.file
    const { id } = req.user
    db(`UPDATE users SET username='${username}', password='${password}',email= '${email}',nickname= '${nickname}' ,userPic='${filename}' WHERE id='${id}'`, (err, data) => {
        if (err || data.affectedRows === 0) return res.send({ code: 400, msg: '用户资料修改失败' })
        res.send({ code: 200, msg: '修改成功' })
    })
})






module.exports = router